from django import template
from bookmarks.models import Bookmark
from blog.models import Post
import re 

register = template.Library()

@register.simple_tag
def active(request, pattern):
  import re
  if re.search(pattern, request.path):
    return 'active'
  return ''


@register.simple_tag
def hexdump(prefix, src, length=16):
  '''
    Found at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502293
  '''
  HEX_FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)])
  N=0; result=''
  while src:
    s,src = src[:length],src[length:]
    hexa = ' '.join(["%02X"%ord(x) for x in s])
    s = s.translate(HEX_FILTER)
    result += "%s %04X   %-*s   %s\n" % (prefix, N, length*3, hexa, s)
    N+=length
  return result



@register.filter
def replace ( string, args ): 
    search  = args.split(args[0])[1]
    replace = args.split(args[0])[2]

    return re.sub( search, replace, string )



class LatestItems(template.Node):
  '''
    loads list of flatpages that should be listed at the bottom 
    of the sidenav
  '''

  def __init__(self):
    pass

  def render(self, context):
    '''
      Get the latest Bookmarks, shove them into context 
    '''

    context['latestBookmarkList'] = []
    context['latestPostList'] = []

    bookmarkList = Bookmark.objects.order_by('-created_date')[:5]
    postList = Post.objects.order_by('-pub_date')[:5]
  
    for bookmark in bookmarkList:
      context['latestBookmarkList'].append(bookmark)

    for post in postList:
      context['latestPostList'].append(post)

    return ''


def do_getLatestItems(parser, token):
  '''
    parser for LatestBookmarks
  '''
  return LatestItems()

register.tag('getLatestItems', do_getLatestItems)
